package signer;

/**
 * @author lizhifeng
 */


import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

public class RSA2Signer {

    private static final String sign_algorithm = "SHA256WithRSA";
    private static final String sign_type = "RSA";

    public byte[] doSign(byte[] content, byte[] privateKey) throws Exception {

        byte[] encodedKey = privateKey;
        KeyFactory keyFactory = KeyFactory.getInstance(sign_type);
        PrivateKey priKey = keyFactory.generatePrivate(new PKCS8EncodedKeySpec(encodedKey));

        Signature signature = Signature.getInstance(getSignAlgorithm());
        signature.initSign(priKey);
        signature.update(content);
        byte[] signed = signature.sign();
        return signed;
    }


    public boolean doVerify(byte[] content, byte[] publicKey, byte[] sign) throws Exception {

        KeyFactory keyFactory = KeyFactory.getInstance(sign_type);
        PublicKey pubKey = keyFactory.generatePublic(new X509EncodedKeySpec(publicKey));

        Signature signature = Signature.getInstance(getSignAlgorithm());
        signature.initVerify(pubKey);
        signature.update(content);
        return signature.verify(sign);
    }

    protected String getSignAlgorithm() {
        return sign_algorithm;
    }

}